package pro.softzhang.algo.lc0;

import pro.softzhang.algo.common.Utils;
import pro.softzhang.algo.flag.knowledge.KBackTracking;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 77. 组合
 * https://leetcode.cn/problems/combinations/description/
 */
@KBackTracking
public class LC77_Combinations {
    public static void main(String[] args) {
        Utils.printInJson(new Solution1().combine(4, 2));
    }

    /**
     *
     */
    static
    class Solution {
        public List<List<Integer>> combine(int n, int k) {
            List<List<Integer>> r = new LinkedList<>();
            LinkedList<Integer> c = new LinkedList<>();
            combine0(n, k, 1, c, r);
            return r;
        }

        public void combine0(int n, int k, int i, LinkedList<Integer> combination, List<List<Integer>> result) {
            if(combination.size() == k) {
                result.add(new LinkedList<>(combination));
                return;
            }

            if(i <= n) {
                combine0(n, k, i + 1, combination, result);
                combination.add(i);

                combine0(n, k, i + 1, combination, result);
                combination.removeLast();
            }
        }
    }

    /**
     *
     */
    static
    class Solution1 {
        public List<List<Integer>> combine(int n, int k) {
            List<Integer> path = new LinkedList<>();
            List<List<Integer>> res = new LinkedList<>();
            dfs(n, k, path, res);
            return res;
        }

        private void dfs(int i , int k, List<Integer> path, List<List<Integer>> res) {
            int d = k - path.size();
            if (d == 0) {
                res.add(new ArrayList<>(path));
                return;
            }

            for (int j = i; j >= d; j--) {
                path.add(j);
                dfs(j - 1, k, path, res);
                path.remove(path.size() - 1);
            }
        }
    }
}
